package net.youpo.Market.UI;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Download.DownloadManager;
import net.youpo.Market.Download.Downloads;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.GlobalVariables;
import net.youpo.Market.Util.Tools;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AppListAdapter extends BaseAdapter {
	private final int REFRESH_LIST = 516;
	private final int REFRESH_TIME = 200;// 刷新间隔
	private BlockingQueue<Runnable> mBlockingQueue = new LinkedBlockingQueue<Runnable>();// 创建线程队列
	private ThreadPoolExecutor mExecutor = new ThreadPoolExecutor(1, 10, 30,
			TimeUnit.SECONDS, mBlockingQueue);// 创建线程池,线程大小1,最大池大小10,线程持续时间30,持续时间单位s，线程队列
	public boolean mFastFlingFlag = false;// 是否正在快速滑动
	public boolean mDownloadThumbnailFlag = true;// 是否在停止滑动的时候下载
	private DownloadManager mDownloadManager;
	private HashMap<String, AppInfoBean> mUpdateList;

	private ArrayList<AppInfoBean> mlist;
	private Context mContext;

	public AppListAdapter(Context context, ArrayList<AppInfoBean> list) {
		this.mContext = context;
		this.mlist = list;
		this.mDownloadManager = new DownloadManager(context);
		this.mUpdateList = GlobalVariables.NEED_UPDATE_APP;
	}

	public void setFastFlingFlag(boolean mFastFlingFlag) {
		this.mFastFlingFlag = mFastFlingFlag;
	}

	public void setDownloadThumbnailFlag(boolean flag) {
		this.mDownloadThumbnailFlag = flag;
	}

	@Override
	public int getCount() {
		return mlist.size();
	}

	@Override
	public Object getItem(int position) {
		return mlist.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		AppHolder mHolder;
		final AppInfoBean appBean = mlist.get(position);

		// if (convertView == null) {
		final LayoutInflater mInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		convertView = mInflater.inflate(R.layout.applist_view, null);
		mHolder = new AppHolder();
		mHolder.icon = (ImageView) convertView.findViewById(R.id.app_icon);
		mHolder.appName = (TextView) convertView.findViewById(R.id.app_Name);
		mHolder.appCat = (TextView) convertView.findViewById(R.id.app_Cat);
		mHolder.appSize = (TextView) convertView.findViewById(R.id.app_size);
		mHolder.appStar = (StarView) convertView
				.findViewById(R.id.app_starView);
		mHolder.download = (LinearLayout) convertView
				.findViewById(R.id.applist_download_btn);
		mHolder.donwloadIcon = (ImageView) convertView
				.findViewById(R.id.downloadIcon);
		mHolder.downloadText = (TextView) convertView
				.findViewById(R.id.downloadText);
		convertView.setTag(mHolder);
		// } else {
		// mHolder = (AppHolder) convertView.getTag();
		// }

		mHolder.appName.setText(appBean.APP_NAME);
		mHolder.appCat.setText(appBean.APP_CAT);
		mHolder.appSize.setText(appBean.APP_SIZE);
		mHolder.appStar.setPoint(Integer.valueOf(appBean.APP_SCORE));
		if (appBean.APP_ICON_BMP == null) {
			mHolder.icon.setImageResource(R.drawable.icon);

			if (!mFastFlingFlag) {
				try {
					mBlockingQueue.put(new Runnable() {
						@Override
						public void run() {
							if (mDownloadThumbnailFlag) {
								mHandler.removeMessages(REFRESH_LIST);
								File file = new File(ConstantsTable.CACHE_PATH
										+ "/" + appBean.APP_ID);
								Bitmap bmp = null;
								if (file.exists()) {// 如果有缓存文件
									bmp = Tools
											.getBitmapFromCache(ConstantsTable.CACHE_PATH
													+ "/" + appBean.APP_ID);
								} else {// 没有缓存就从网络获取
									HttpConnection hc = new HttpConnection();
									bmp = hc.getNetworkBitmap(appBean.APP_ICON);

									Tools.saveBmpToSd(bmp, appBean.APP_ID);// 保存至缓存
								}
								Drawable drawable = new BitmapDrawable(bmp);
								appBean.APP_ICON_BMP = drawable;
								mHandler.sendEmptyMessageDelayed(REFRESH_LIST,
										REFRESH_TIME);
							}
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				executeDownloadBitmapThread();
			}
		} else {
			mHolder.icon.setImageDrawable(appBean.APP_ICON_BMP);
		}

		for (AppInfoBean aib : mUpdateList.values()) {
			if (aib.APP_NAME.equals(appBean.APP_NAME)) {
				mHolder.donwloadIcon
						.setBackgroundResource(R.drawable.app_update);
				mHolder.downloadText.setText("更新");
				break;
			}
		}

		mHolder.download.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				AppInfoBean aib = mlist.get(position);
				mDownloadManager.insertDownload(aib, Downloads.TYPE_DOWNLOAD);
				Log.d("H3c", mlist.get(position).APP_NAME + "..download");
				notifyDataSetChanged();
			}
		});

		final File file = new File(ConstantsTable.DOWNLOAD_PATH + "/"
				+ appBean.APP_ID + ".apk");
		if (file.exists()) {
			mHolder.donwloadIcon
					.setBackgroundResource(R.drawable.download_install);
			mHolder.downloadText.setText("安装");
			mHolder.download.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setDataAndType(
							Uri.parse("file://" + file.getAbsolutePath()),
							"application/vnd.android.package-archive");
					mContext.startActivity(i);
					notifyDataSetChanged();
				}
			});
		}
		return convertView;
	}

	public void executeDownloadBitmapThread() {
		Runnable runnable = mBlockingQueue.poll();
		if (runnable != null) {
			mExecutor.execute(runnable);
		}
	}

	public void recycle() {
		mExecutor.shutdown();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case REFRESH_LIST:
				notifyDataSetChanged();
				break;
			default:
			}
		}
	};

	class AppHolder {
		ImageView icon;
		TextView appName;
		TextView appCat;
		TextView appSize;
		StarView appStar;
		LinearLayout download;
		ImageView donwloadIcon;
		TextView downloadText;
	}
}